package com.hwhhhh.mygrad;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hwhhhh.mygrad.adapter.SchoolBuildingAdapter;
import com.hwhhhh.mygrad.adapter.StickHeaderAdapter;
import com.hwhhhh.mygrad.api.Api;
import com.hwhhhh.mygrad.api.ApiCallback;
import com.hwhhhh.mygrad.api.ApiConfig;
import com.hwhhhh.mygrad.dto.FreeClsDTO;
import com.hwhhhh.mygrad.entity.RespDataArr;
import com.hwhhhh.mygrad.dto.UserDTO;
import com.hwhhhh.mygrad.fragment.ScreenDialogFragment;
import com.hwhhhh.mygrad.utils.MyDatePickerDialog;
import com.hwhhhh.mygrad.utils.StringUtils;
import com.hwhhhh.mygrad.view.IconfontView;
import com.hwhhhh.mygrad.view.RoundAngleImageView;
import com.hwhhhh.mygrad.view.RoundImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class HomeActivity extends BaseActivity implements View.OnClickListener {
    public static final int JXQ = 0;
    public static final int XY = 1;
    public static final int QH = 2;
    private static final String TAG = "HomeActivity";

    private NavigationView nvHomeMenu;
    // 日期、空教室查询条件、固定头部
    private TextView tvDate, tvHomeCondition, tvClsBar, tvUserName, tvUserTarget, tvUserLevel, tvSort;
    private IconfontView icMenu, icSort;
    private DrawerLayout drawerLayout;
    private MyDatePickerDialog datePickerDialog;
    private LinearLayout linearLayoutHomeCondition, clsBarLayout;
    public int curYear, curMonth, curDay, campus = 1, start = 0, end = 12, sortState = 0; // 小营0，健翔桥1，清河2，第一节0，第十三节12
    private ScreenDialogFragment dialogFragment;
    private RecyclerView rvClsList, rvSchoolBuilding;
    private SwipeRefreshLayout refreshLayout;
    private SchoolBuildingAdapter schoolBuildingAdapter;
    private RoundImageView ivProfilePhoto;
    private StickHeaderAdapter stickHeaderAdapter;
    private List<FreeClsDTO> freeClsList, curFreeClsList;
    private EditText etSearch;
    private UserDTO user;

    @Override
    protected void initView() {
        nvHomeMenu = findViewById(R.id.nv_home_menu);
        tvDate = findViewById(R.id.tv_date);
        icMenu = findViewById(R.id.ic_menu);
        drawerLayout = findViewById(R.id.home_drawer_layout);
        linearLayoutHomeCondition = findViewById(R.id.home_condition);
        tvHomeCondition = findViewById(R.id.tv_home_condition);
        rvClsList = findViewById(R.id.rv_cls_list);
        rvSchoolBuilding = findViewById(R.id.rv_school_building);
        refreshLayout = findViewById(R.id.cls_list_container);
        etSearch = findViewById(R.id.et_home_search);
        tvSort = findViewById(R.id.tv_sort);
        icSort = findViewById(R.id.ic_sort);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        user = (UserDTO) bundle.get("user");
        // 将用户信息序列化存进sp中，要取出时从sp取出反序列化即可
        saveStringToSp("user", new Gson().toJson(user));
        setBarColor(R.color.brand_color);
        icMenu.setOnClickListener(this);
        tvDate.setOnClickListener(this);
        tvSort.setOnClickListener(this);
        linearLayoutHomeCondition.setOnClickListener(this);
        // 初试化右上角日期
        Calendar calendar = Calendar.getInstance();
        curYear = calendar.get(Calendar.YEAR);
        curMonth = calendar.get(Calendar.MONTH) + 1;
        curDay = calendar.get(Calendar.DAY_OF_MONTH);
        tvDate.setText(generateDateText(curYear, curMonth, curDay));
        // 教学楼的recyclerview
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvSchoolBuilding.setLayoutManager(layoutManager);
        schoolBuildingAdapter = new SchoolBuildingAdapter(this, StringUtils.getSchoolBuilding(campus, 0));
        rvSchoolBuilding.setAdapter(schoolBuildingAdapter);
        // 下拉刷新数据
        refreshLayout.setOnRefreshListener(this::requestData);
        // 侧拉菜单的点击事件
        nvHomeMenu.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                if (id == R.id.nav_message) {
                    navigateTo(MessageActivity.class);
                } else if (id == R.id.nav_history) {
                    navigateTo(HistoryActivity.class, "user", user);
                } else if (id == R.id.nav_shopping) {
                    navigateTo(ShoppingActivity.class);
                } else if (id == R.id.nav_setting) {
                    navigateTo(SettingNewActivity.class);
                }
                return true;
            }
        });
        // 搜索框的焦点，当获取焦点时则进入搜索界面
        etSearch.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                navigateTo(SearchActivity.class);
                etSearch.clearFocus();
            }
        });
        requestData();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ic_menu) {   // 点击HOME页面左上角的menu图标时进入侧拉菜单
            drawerLayout.openDrawer(GravityCompat.START);
            if (tvUserName == null) {   // 当为空时，还未获取各个空间
                ivProfilePhoto = findViewById(R.id.iv_profile_photo);
                tvUserName = findViewById(R.id.tv_user_name);
                tvUserLevel = findViewById(R.id.tv_user_level);
                tvUserTarget = findViewById(R.id.tv_user_target);
                // 菜单头部，即用户头像、名称等
                LinearLayout menuUserInfo = findViewById(R.id.menu_user_info);
                // 点击头部时进入用户资料界面
                menuUserInfo.setOnClickListener(v1 -> navigateTo(UserInfoActivity.class, "user", user));
            }
            // 加载用户头像、用户名、用户目标
            Glide.with(this).load(user.getProfilePhoto()).into(ivProfilePhoto);
            tvUserName.setText(user.getName());
            tvUserTarget.setText(user.getTarget());
        } else if (id == R.id.tv_date) {
            if (datePickerDialog == null) {
                datePickerDialog = new MyDatePickerDialog(this, (datePicker, i, i1, i2) -> {
                    curYear = i; curMonth = i1 + 1; curDay = i2;
                    tvDate.setText(generateDateText(curYear, curMonth, curDay));
                    requestData();
                }, curYear, curMonth - 1, curDay);
            }
            datePickerDialog.show();
        } else if (id == R.id.home_condition) {
            dialogFragment = ScreenDialogFragment.getInstance(campus, start, end);
            dialogFragment.setCallback(() -> {
                schoolBuildingAdapter.setSbs(StringUtils.getSchoolBuilding(campus, 0));
                schoolBuildingAdapter.notifyDataSetChanged();
                tvHomeCondition.setText(dialogFragment.getTitleText(campus, start, end));
                refreshLayout.setRefreshing(true);
                requestData();
            });
            dialogFragment.show(getSupportFragmentManager(), ScreenDialogFragment.class.getSimpleName());
        } else if (id == R.id.tv_sort) {
            switch (sortState) {
                case 0: // 此时为默认排序状态，点击进行升序排序
                    icSort.setText(getResources().getString(R.string.ic_arrow_up));
                    icSort.setTextColor(getResources().getColor(R.color.bold_font_color));
                    sortState = 1;
                    sortFreeList(1);
                    break;
                case 1: // 此时为升序排序，点击进行降序排序
                    icSort.setText(getResources().getString(R.string.ic_arrow_down));
                    icSort.setTextColor(getResources().getColor(R.color.bold_font_color));
                    sortState = 2;
                    sortFreeList(-1);
                    break;
                case 2: // 此时为升序排序，点击复原
                    icSort.setText(getResources().getString(R.string.ic_sorting));
                    icSort.setTextColor(getResources().getColor(R.color.main_font_color));
                    sortState = 0;
                    sortFreeList(0);
                    break;
            }
        }
    }

    private void requestData() {
        Log.d(TAG, "requestData: start" + start + " end: " + end);
        String freeDate = generateDateText(curYear, curMonth, curDay);
        HashMap<String, Object> params = new HashMap<>();
        params.put("freeDate", freeDate);
        params.put("campus", campus + 1);
        params.put("start", start + 1);
        params.put("end", end + 1);
        Api.config(ApiConfig.FREE_CLSLIST, params).getRequest(this, new ApiCallback() {
            @Override
            public void onSuccess(String res) {
                RespDataArr<FreeClsDTO> dataArr = StringUtils.fromJsonArr(res, new TypeToken<RespDataArr<FreeClsDTO>>(){}.getType());
//                RespData respData = StringUtils.fromJson(res, RespData.class);
                if (dataArr.getCode() == 200) {
//                    Type type = new TypeToken<List<FreeClsEntity>>(){}.getType();
//                    List<FreeClsEntity> freeClsList = StringUtils.fromJson(respData.getData().toString(), type);
                    freeClsList = dataArr.getData();
                    if (freeClsList.size() == 0) {
                        HomeActivity.this.runOnUiThread(() -> {
                            if (stickHeaderAdapter != null) {
                                stickHeaderAdapter.getData().clear();
                                stickHeaderAdapter.notifyDataSetChanged();
                            }
                            showToast("今天没有此条件的空教室哦~");
                        });
                        if (refreshLayout.isRefreshing()) refreshLayout.setRefreshing(false);
                        return;
                    }
                    freeClsList = addCategoryTitle(freeClsList);
                    // 更新视图
                    HomeActivity.this.runOnUiThread(() -> {
                        // recyclerview展示
                        LinearLayoutManager layoutManager = new LinearLayoutManager(HomeActivity.this);
                        rvClsList.setLayoutManager(layoutManager);
                        Log.d(TAG, "onSuccess: freeClsList's size is " + freeClsList.size());
                        if (stickHeaderAdapter == null) {
                            stickHeaderAdapter = new StickHeaderAdapter(HomeActivity.this, freeClsList, StringUtils.getSchoolBuilding(campus,1));
                            curFreeClsList = freeClsList;
                            rvClsList.setAdapter(stickHeaderAdapter);
                        } else {
                            stickHeaderAdapter.setData(freeClsList);
                            curFreeClsList = freeClsList;
                            stickHeaderAdapter.notifyDataSetChanged();
                        }
                        // 设置教学楼点击监听，根据点击的位置对教室列表进行相应的操作
                        schoolBuildingAdapter.setClsSBListener(position -> {
                            if (freeClsList.size() == 0) {
                                showToast("今天没有此条件的空教室哦~");
                                return;
                            }
                            if (position == 0) {
                                stickHeaderAdapter.setData(freeClsList);
                                curFreeClsList = freeClsList;
                            } else {
                                List<FreeClsDTO> temp = new ArrayList<>();
                                FreeClsDTO title = new FreeClsDTO();
                                title.setSchoolBuilding(-1);
                                temp.add(title);
                                for (FreeClsDTO entity : freeClsList) {
                                    if (entity.getSchoolBuilding() == position) temp.add(entity);
                                }
                                if (temp.size() == 1) {
                                    showToast("今天没有该教学楼的空教室哦~");
                                    stickHeaderAdapter.setData(new ArrayList<>());
                                    stickHeaderAdapter.notifyDataSetChanged();
                                    return; // 此时没有该类型教学楼
                                }
                                curFreeClsList = temp;
                                stickHeaderAdapter.setData(temp);
                            }
                            stickHeaderAdapter.notifyDataSetChanged();
                        });
                        if (refreshLayout.isRefreshing()) refreshLayout.setRefreshing(false);
                    });
                } else {
                    Looper.prepare();
                    Toast.makeText(HomeActivity.this, "请求失败，请稍后！",Toast.LENGTH_LONG).show();
                    if (refreshLayout.isRefreshing()) refreshLayout.setRefreshing(false);
                    Looper.loop();
                }
            }

            @Override
            public void onFailure(Exception e) {
                Looper.prepare();
                Toast.makeText(HomeActivity.this, "请求失败！",Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        });
    }

    private List<FreeClsDTO> addCategoryTitle(List<FreeClsDTO> data) {

        List<FreeClsDTO> res = new ArrayList<>();
        int preSB = data.get(0).getSchoolBuilding();
        FreeClsDTO titleEntity = new FreeClsDTO();
        titleEntity.setSchoolBuilding(-1);
        res.add(titleEntity);
        for (FreeClsDTO entity : data) {
            int sb = entity.getSchoolBuilding();
            if (preSB != sb) {
                preSB = sb;
                titleEntity = new FreeClsDTO();
                titleEntity.setSchoolBuilding(-1);
                res.add(titleEntity);
            }
            res.add(entity);
        }
        return res;
    }

    /**
     * 通过占用率进行排序
     * @param compareType 排序的类型，1为升序，0为复原，-1为降序。
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void sortFreeList(int compareType) {
        if (stickHeaderAdapter == null || freeClsList.isEmpty()) return;
        // 当为0时，复原
        if (compareType == 0) {
            stickHeaderAdapter.setData(curFreeClsList);
            stickHeaderAdapter.notifyDataSetChanged();
            return;
        }
        // 获取当前展示的信息,其可能是经过排序的
        List<FreeClsDTO> data = stickHeaderAdapter.getData();
        // 用来存放最终结果，即各个教学楼经过排序后的结果
        List<FreeClsDTO> res = new ArrayList<>();
        List<FreeClsDTO> temp = new ArrayList<>();
        for (FreeClsDTO dto : data) {
            if (dto.getSchoolBuilding() == -1) {
                // 当res为空、temp为空时，表明此时为第一组，不进行排序
                // 当res为空，temp不为空时，表明此时不为第一组，需要将temp进行排序然后加进res中，然后清空temp进行下一组排序
                // 当res不为空，temp不为空，表明这一组已经全部加入，需要进行排序。
                if (!temp.isEmpty()) {
                    temp.sort((o1, o2) -> {
                        float prop1 = (float)o1.getOccupyNum() / o1.getCapacity();
                        float prop2 = (float)o2.getOccupyNum() / o2.getCapacity();
                        float div = prop1 - prop2;
                        if (div > 0) {
                            if (compareType > 0) return 1;
                            return -1;
                        } else if (div < 0){
                            if (compareType > 0) return -1;
                            return 1;
                        } else {
                            return 0;
                        }
                    });
                    res.add(new FreeClsDTO(-1));
                    res.addAll(temp);
                    temp.clear();
                }
                continue;
            }
            temp.add(dto);
        }
        // 将最后的一组排序
        temp.sort((o1, o2) -> {
            float prop1 = (float)o1.getOccupyNum() / o1.getCapacity();
            float prop2 = (float)o2.getOccupyNum() / o2.getCapacity();
            float div = prop1 - prop2;
            if (div > 0) {
                if (compareType > 0) return 1;
                return -1;
            } else if (div < 0){
                if (compareType > 0) return -1;
                return 1;
            } else {
                return 0;
            }
        });
        res.add(new FreeClsDTO(-1));
        res.addAll(temp);
        stickHeaderAdapter.setData(res);
        stickHeaderAdapter.notifyDataSetChanged();
    }

    private void moveToPosition(LinearLayoutManager manager, RecyclerView recyclerView, int n) {
        int firstPosition = manager.findFirstVisibleItemPosition();
        int lastPosition = manager.findLastVisibleItemPosition();

        if (n < firstPosition) {
            recyclerView.smoothScrollToPosition(n);
            Log.d(TAG, "moveToPosition: 1》》》》》first: " + firstPosition + " last: " + lastPosition + " n: " + n);
        } else if (n <= lastPosition) {
            int top = recyclerView.getChildAt(n - firstPosition).getTop();
            recyclerView.smoothScrollBy(0, top);
            Log.d(TAG, "moveToPosition: 2》》》》》》first: " + firstPosition + " last: " + lastPosition + " n: " + n);
        } else {
            recyclerView.smoothScrollToPosition(n);
            Log.d(TAG, "moveToPosition: 3》》》》》》first: " + firstPosition + " last: " + lastPosition + " n: " + n);
        }
    }

    public String generateDateText(int year, int month, int day) {
        return year + "-" + month + "-" + day;
    }

    public void setCampus(int campus) {
        this.campus = campus;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public void setEnd(int end) {
        this.end = end;
    }
}